package com.kalvan.web.feign;


import cn.hutool.http.HttpStatus;
import feign.Request;
import feign.Response;
import feign.Util;
import org.slf4j.Logger;

import java.io.IOException;

import static feign.Util.UTF_8;
import static feign.Util.decodeOrDefault;

/**
 * desc
 *
 * @author chenliang
 */
public class FeignLogger extends feign.Logger {
    private final Logger logger;

    public FeignLogger(Logger logger) {
        this.logger = logger;
    }

    @Override
    protected void log(String configKey, String format, Object... args) {
        if (logger.isInfoEnabled()) {
            logger.info(String.format(methodTag(configKey) + format, args));
        }
    }

    @Override
    protected void logRequest(String configKey, Level logLevel, Request request) {
        String bodyText = null;
        if (request.body() != null) {
            bodyText = request.charset() != null ? new String(request.body(), request.charset()) : null;
        }
        log(configKey, "接口入参：%s", bodyText != null ? bodyText : "");
    }

    @Override
    protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime) throws IOException {
        int status = response.status();
        Response.Body body = response.body();
        if (body != null && !(status == HttpStatus.HTTP_NO_CONTENT || status == HttpStatus.HTTP_RESET)) {
            byte[] bodyData = Util.toByteArray(body.asInputStream());
            log(configKey, "接口响应：%s", decodeOrDefault(bodyData, UTF_8, ""));
            return response.toBuilder().body(bodyData).build();
        } else {
            log(configKey, "接口响应：%s", "");
        }
        return response;
    }

    @Override
    protected IOException logIOException(String configKey, Level logLevel, IOException ioe, long elapsedTime) {
        return ioe;
    }
}
